import React, { PureComponent, Component } from 'react';
import { Card, message, Button } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import _ from 'lodash';
import moment from 'moment';
import router from 'umi/router';
import { traceLifecycle } from 'react-lifecycle-visualizer';
import ProjectsPath from '@/components/ProjectsPath';
import HeaderRenderer from '@/components/BaseTable/HeaderRenderer';
import CurrentStage from '../../components/CurrentStage';
import PageEmpty from '@/components/PageEmpty';
import AuthorizedButton from '@/components/AuthorizedButton';
import PageTop from './components/PageTop';
import * as apis from '@/services/PriceMgr';
import { showConfirm } from '@/utils/utils';
import { utils, BaseTable, TextWithTags } from '@/components/BaseTable';
import IdCellRenderer from './components/IdCellRenderer';
import TagsCellRenderer from './components/TagsCellRenderer';
import AveragePriceCellRenderer from './components/AveragePriceCellRenderer';
import AreaCellRenderer from './components/AreaCellRenderer';
import NumCellRenderer from './components/NumCellRenderer';
import CopyHouseComponent from './components/CopyHouseComponent';
import CopyHousePriceComponent from './components/CopyHousePriceComponent';
import CopyPriceComponent from './components/CopyPriceComponent';
import BatchEditComponent from './components/BatchEditComponent';
import Drawer from '../../components/Drawer';
import * as treeUtils from './utils/treeUtils';
import { handlerMatomoEvent } from '@/utils/matomo';

@connect(state => ({
  items: state.PriceManageItems,
  versions: state.PriceManageVersions,
  currentUser: state.user.currentUser,
  orgStructure: state.orgStructure,
  agentInfo: state.AgentInfo.agentInfo,
}))
@traceLifecycle
export default class PriceManage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      emptyMsg: '版本数据加载中...',
      copyAreaParts: [],
      loading: {
        create: false,
        save: false,
        assessment: false,
      },
      fixedColumns: [],
      showCopyComponent: false,
      rowData: {},
      subtractHeight: props.match.params.edit ? '160px' : '210px',
      titleTree: [
        {
          name:
            props.match.params.category === 'investment'
              ? '分期/组团/产品构成/供应批次'
              : '分期/组团/业态/楼栋',
          key: 'name',
          colspan: 1,
          rowspan: 3,
        },
        {
          name: '供货日期',
          key: 'supplyDate',
          colspan: 1,
          rowspan: 3,
        },
        {
          name:
            props.match.params.category === 'investment'
              ? '经营方式/装修标准/属性标签'
              : '产品属性/面积段',
          key: 'tags',
          colspan: 1,
          rowspan: 3,
        },
        {
          name: '货值(不含未推售车位)',
          key: 'values1',
          colspan: 4,
          rowspan: 1,
        },
        {
          name: '未推售车位货值',
          key: 'values2',
          colspan: 2,
          rowspan: 1,
        },
      ],
    };
  }

  async componentDidMount() {
    const { match } = this.props;
    this.clearItems(this.props);
    this.clearVersions(this.props);
    this.getVersions(this.props);
    this.getVersionsChangeInfo(this.props);
    if (match.params.version) {
      this.clearItems(this.props);
      this.getItems(this.props);
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.match.params.category !== nextProps.match.params.category) {
      const props = nextProps;
      const titleTree = [
        {
          name:
            props.match.params.category === 'investment'
              ? '分期/组团/产品构成/供应批次'
              : '分期/组团/业态/楼栋',
          key: 'name',
          colspan: 1,
          rowspan: 3,
        },
        {
          name: '供货日期',
          key: 'supplyDate',
          colspan: 1,
          rowspan: 3,
        },
        {
          name:
            props.match.params.category === 'investment'
              ? '经营方式/装修标准/属性标签'
              : '产品属性/面积段',
          key: 'tags',
          colspan: 1,
          rowspan: 3,
        },
        {
          name: '货值(不含未推售车位)',
          key: 'values1',
          colspan: 4,
          rowspan: 1,
        },
        {
          name: '未推售车位货值',
          key: 'values2',
          colspan: 2,
          rowspan: 1,
        },
      ];
      this.setState({ titleTree });
    }
    // match变动
    if (
      this.props.match.params.project !== nextProps.match.params.project ||
      this.props.match.params.stage !== nextProps.match.params.stage ||
      this.props.match.params.category !== nextProps.match.params.category
    ) {
      this.clearItems(nextProps);
      this.clearVersions(nextProps);
      // console.log(nextProps.match.params.category, 'nextProps.match.params.category');
      this.getVersions(nextProps);
      this.getVersionsChangeInfo(nextProps);
    }

    if (
      nextProps.match.params.version &&
      this.props.match.params.version !== nextProps.match.params.version
    ) {
      this.clearItems(nextProps);
      this.getItems(nextProps);
      this.getVersions(nextProps);
      this.getVersionsChangeInfo(nextProps);
    }
  }

  calculateTableHeader = () => {
    const { versionDetail } = this.props.items;
    const editing = !!this.props.match.params.edit;
    const self = this;
    const fixedColumns = [
      {
        key: 'name',
        dataKey: 'name',
        title: '',
        width: 250,
        frozen: 'left',
        headerRenderer: () => (
          <div>
            {self.props.match.params.category === 'investment'
              ? '分期/组团/产品构成/供应批次'
              : '分期/组团/业态/楼栋'}
          </div>
        ),
        dataGetter: ({ rowData }) => {
          // TODO 待确认
          let text = rowData.name;
          if (rowData.type === 'org_house_package') {
            text = rowData.areaPart;
          }
          if (rowData.type === 'org_salingparking') {
            text = '可售车位';
          }
          if (rowData.type === 'org_sale_parking') {
            text = '已售车位';
          }
          if (rowData.type === 'org_not_sale_parking') {
            text = '已定价未售车位';
          }
          if (rowData.type === 'org_forsaleparking') {
            text = '未推售车位';
          }
          const result = {
            // text: rowData.name,
            text,
            // number: 1000,
          };
          result.textFirst = true;
          if (
            !rowData.businessTypeName ||
            rowData.businessTypeName === '可售' ||
            rowData.businessTypeName === '阶段性自持'
          ) {
            if (`${rowData.isSupply}` === '0') {
              result.tags = [{ text: '未供', color: 'orange', border: true }];
            }
            if (`${rowData.isSupply}` === '1') {
              result.tags = [{ text: '已供', color: 'green' }];
            }
          }
          return result;
        },
        cellRenderer: (
          <IdCellRenderer
            showCopyPriceComponent={element => self.showCopyPriceComponent(element)}
            showCopyHouseComponent={element => self.showCopyHouseComponent(element)}
            // handleCopyPrice={e =>
            //   self.props.match.params.category === 'investment'
            //     ? self.showCopyPriceComponent(e)
            //     : self.handleCopyPrice(e)
            // }
            isMarketing={self.state.isMarketing}
            category={self.props.match.params.category}
            editing={editing}
            batchAdjust={versionDetail?.batchAdjust}
          />
        ),
      },
      {
        key: 'supplyDate',
        dataKey: 'supplyDate',
        title: '',
        width: 110,
        align: 'center',
        headerRenderer: () => <div>供货日期</div>,
        dataGetter: ({ rowData }) => {
          if (
            !rowData.businessTypeName ||
            rowData.businessTypeName === '可售' ||
            rowData.businessTypeName === '阶段性自持'
          ) {
            if (!_.isEmpty(rowData.supplyDate)) {
              return moment(rowData.supplyDate).format('YYYY-MM-DD');
            }
          }
        },
      },
      {
        key: 'tags',
        dataKey: 'tags',
        title: '',
        width: 210,
        minWidth: 180,
        headerRenderer: () => (
          <div>
            {this.props.match.params.category === 'investment'
              ? '经营方式/装修标准/属性标签'
              : '产品属性/面积段'}
          </div>
        ),
        dataGetter: ({ rowData }) => {
          const text = rowData.areaPart ? rowData.areaPart : null;
          const tags = [];
          if (rowData.businessTypeName) {
            tags.push({ text: rowData.businessTypeName, color: 'orange' });
          }
          if (rowData.freeTypeName) {
            tags.push({ text: rowData.freeTypeName, color: 'blue' });
          }
          if (rowData.proTypeName) {
            tags.push({ text: rowData.proTypeName, color: 'gray' });
          }
          return {
            tags,
            text,
            textFirst: true,
          };
        },
        cellRenderer: (
          <TagsCellRenderer
            isMarketing={self.state.isMarketing}
            category={self.props.match.params.category}
            editing={editing}
            batchAdjust={versionDetail?.batchAdjust}
          />
        ),
      },
      {
        key: 'averagePrice',
        dataKey: 'averagePrice',
        title: '',
        align: 'right',
        width: 150,
        dataGetter: ({ rowData }) => {
          const number = [];
          let tags = [];
          if (rowData.type === 'org_forsaleparking') {
            tags = [{ text: '参考', color: 'pink' }];
            number.push(rowData.averagePrice_parking);
          } else if (
            ((rowData.type === 'org_build' || rowData.type === 'org_product') &&
              !!rowData.isParking) ||
            rowData.type === 'org_salingparking' ||
            rowData.type === 'org_sale_parking' ||
            rowData.type === 'org_not_sale_parking'
          ) {
            number.push(rowData.averagePrice_parking);
          } else if (
            (rowData.type === 'org_build' ||
              rowData.type === 'org_product' ||
              rowData.type === 'org_house_package') &&
            !rowData.isParking
          ) {
            number.push(rowData.averagePrice_house);
          } else {
            if (_.isNumber(rowData.averagePrice_house)) {
              number.push(rowData.averagePrice_house);
            }
            if (_.isNumber(rowData.averagePrice_parking)) {
              number.push(rowData.averagePrice_parking);
            }
          }
          return {
            tags,
            number,
          };
        },
        cellRenderer: (
          <AveragePriceCellRenderer
            precision={0}
            isMarketing={self.state.isMarketing}
            category={self.props.match.params.category}
            editing={editing}
            isBatchAdjust={self.props.items.versionDetail?.batchAdjust}
          />
        ),
        headerRenderer: () => (
          <div>
            <HeaderRenderer {...this.props} type={2}>
              <div>均价</div>
              <div>(元/平米,个)</div>
            </HeaderRenderer>
          </div>
        ),
      },
      {
        key: 'num',
        dataKey: 'num',
        title: '',
        align: 'right',
        width: 100,
        dataGetter: ({ rowData }) => {
          let number = [];
          if (rowData.type === 'org_forsaleparking') {
            number = [];
          } else if (
            ((rowData.type === 'org_build' || rowData.type === 'org_product') &&
              !!rowData.isParking) ||
            rowData.type === 'org_salingparking' ||
            rowData.type === 'org_sale_parking' ||
            rowData.type === 'org_not_sale_parking'
          ) {
            number = rowData.num_parking;
          } else if (
            (rowData.type === 'org_build' ||
              rowData.type === 'org_product' ||
              rowData.type === 'org_house_package') &&
            !rowData.isParking
          ) {
            number = rowData.num_house;
          } else {
            if (_.isNumber(rowData.num_house)) {
              number.push(rowData.num_house);
            }
            if (_.isNumber(rowData.num_parking)) {
              number.push(rowData.num_parking);
            }
          }
          return number;
        },
        cellRenderer: (
          <NumCellRenderer
            step={1.0}
            isMarketing={self.state.isMarketing}
            category={self.props.match.params.category}
            editing={editing}
            batchAdjust={versionDetail?.batchAdjust}
          />
        ),
        headerRenderer: () => (
          <div>
            <HeaderRenderer {...this.props} type={1}>
              <div>套数/车位数</div>
              <div>(套/个)</div>
            </HeaderRenderer>
          </div>
        ),
      },
      {
        key: 'saleArea',
        dataKey: 'saleArea',
        title: '',
        align: 'right',
        dataGetter: ({ rowData }) => {
          let result = rowData.saleArea_sum;
          if (_.isNumber(rowData.saleArea) && rowData.isParking !== 1) {
            result = rowData.saleArea;
          }
          return result;
        },
        cellRenderer: (
          <AreaCellRenderer
            isMarketing={self.state.isMarketing}
            category={self.props.match.params.category}
            editing={editing}
            precision={2}
            batchAdjust={versionDetail?.batchAdjust}
          />
        ),
        headerRenderer: () => (
          <div>
            {/* <HeaderRenderer {...this.props} type={4}> */}
            <div>可售面积</div>
            <div>(平米)</div>
            {/* </HeaderRenderer> */}
          </div>
        ),
        width: 100,
      },
      {
        key: 'nocontainCommodityValue',
        title: '',
        align: 'right',
        width: 200,
        dataGetter: ({ rowData }) => {
          let number = [];
          if (rowData.type === 'org_forsaleparking') {
            number = null;
          } else if (
            ((rowData.type === 'org_build' || rowData.type === 'org_product') &&
              !!rowData.isParking) ||
            rowData.type === 'org_salingparking' ||
            rowData.type === 'org_sale_parking' ||
            rowData.type === 'org_not_sale_parking'
          ) {
            number = _.sum([rowData.sum_parking_saling]) / 10000;
          } else if (
            (rowData.type === 'org_build' ||
              rowData.type === 'org_product' ||
              rowData.type === 'org_house_package') &&
            !rowData.isParking
          ) {
            number = _.sum([rowData.sum_house]) / 10000;
          } else {
            if (_.isNumber(rowData.sum_parking_saling) && _.isNumber(rowData.sum_house)) {
              number.push(_.sum([rowData.sum_parking_saling, rowData.sum_house]) / 10000);
            }
            if (_.isNumber(rowData.sum_house)) {
              number.push(rowData.sum_house / 10000);
            }
            if (_.isNumber(rowData.sum_parking_saling)) {
              number.push(_.sum([rowData.sum_parking_saling]) / 10000);
            }
          }
          return {
            number,
          };
        },
        cellRenderer: (
          <TextWithTags
            isMarketing={self.state.isMarketing}
            category={self.props.match.params.category}
            precision={0}
          />
        ),
        headerRenderer: () => (
          <div>
            <HeaderRenderer {...this.props} type={3}>
              <div>金额</div>
              <div>(万元：合计/房源/车位)</div>
            </HeaderRenderer>
          </div>
        ),
      },
      {
        key: 'num_parking_forsale',
        dataKey: 'num_parking_forsale',
        title: '',
        align: 'right',
        width: 100,
        dataGetter: ({ rowData }) => {
          let number = [];
          if (rowData.type === 'org_forsaleparking') {
            number = rowData.num_parking_forsale;
          } else if (rowData.num_parking_forsale) {
            number.push(rowData.num_parking_forsale);
          }
          return number;
        },
        cellRenderer: (
          <NumCellRenderer
            step={1.0}
            isMarketing={self.state.isMarketing}
            category={self.props.match.params.category}
            editing={false}
          />
        ),
        headerRenderer: () => (
          <div>
            <div>车位数</div>
            <div>(个数)</div>
          </div>
        ),
      },
      {
        key: 'sum_parking_forsale',
        title: '',
        align: 'right',
        width: 120,
        dataGetter: ({ rowData }) => {
          let number = [];
          let tags = [];
          if (rowData.type === 'org_forsaleparking') {
            tags = [{ text: '参考', color: 'pink' }];
            number = rowData.sum_parking_forsale / 10000;
          } else if (rowData.sum_parking_forsale) {
            tags = [{ text: '参考', color: 'pink' }];
            number.push(rowData.sum_parking_forsale / 10000);
          }
          return {
            tags,
            number,
          };
        },
        cellRenderer: (
          <TextWithTags
            isMarketing={self.state.isMarketing}
            category={self.props.match.params.category}
            precision={0}
          />
        ),
        headerRenderer: () => (
          <div>
            <HeaderRenderer {...this.props} text="提示信息">
              <div>金额</div>
              <div>(万元)</div>
            </HeaderRenderer>
          </div>
        ),
      },
    ];
    this.setState({ fixedColumns });
  };

  getVersions = (props, callback) => {
    const { dispatch, match } = props;
    const params = {
      projectFid: match.params.stage,
      versionType: props.match.params.category,
    };

    const self = this;
    self.setState({ emptyMsg: '版本数据加载中...' });
    if (!callback) {
      callback = versions => {
        // 如果:version==null 跳转第一个version
        if (versions && !match.params.version) {
          router.replace(
            `/ValueManage/PriceManage/${match.params.level1}/${match.params.level2}/${match.params.project}/${match.params.stage}/${match.params.category}/${versions[0].versionId}`,
          );
        } else if (versions && match.params.version) {
          router.replace(`${this.props.location.pathname}`);
        } else {
          self.setState({ emptyMsg: '版本不存在，请先创建新版本' });
        }
      };
    }
    // 获取versions
    dispatch({
      type: 'PriceManageVersions/fetch',
      payload: { params },
      callback,
    });
  };

  clearItems = props => {
    const { dispatch } = props;
    dispatch({
      type: 'PriceManageItems/clear',
    });
  };

  clearVersions = props => {
    const { dispatch } = props;
    dispatch({
      type: 'PriceManageVersions/clear',
    });
  };

  getItems = props => {
    const self = this;
    const { dispatch, match } = props;
    if (match.params.version) {
      const params = {
        versionId: match.params.version,
        // stage: match.params.stage,
      };
      dispatch({
        type: 'PriceManageItems/init',
        payload: {
          params,
          category: props.match.params.category,
        },
        callback: data => {
          self.setState({ emptyMsg: '' });
          if (_.isEmpty(data)) {
            self.setState({ emptyMsg: '暂无版本，请先创建新版本' });
          }
          this.calculateTableHeader();
        },
      });
    }
  };

  // 根据分期id获取最新的待办信息
  getVersionsChangeInfo = props => {
    const { dispatch, match } = props;
    dispatch({
      type: 'AgentInfo/init',
      payload: {
        params: {
          stagesId: match.params.stage,
        },
      },
    });
  };

  showCopyPriceComponent = rowData => {
    if (!rowData.averagePrice_house) {
      message.warning('均价未填写');
      return;
    }
    this.setState({
      showCopyComponent: true,
      rowData,
    });
  };

  handleCopyClick = rowData => {
    const { dispatch } = this.props;
    const { category } = this.props.match.params;
    dispatch({
      type: 'PriceManageItems/saveRows',
      payload: { rowData, category, isMarketing: this.state.isMarketing },
    });
    this.handleCopyPriceClose();
  };

  // Begin---跳转发起审批
  handlerApprove = approvedType => {
    const { dispatch, match } = this.props;
    const params = {
      projectId: match.params.project,
      approvedType,
    };
    dispatch({
      type: 'PriceManageApprove/fetch',
      payload: { params },
      callback: data => {
        // 货值审批-埋点
        handlerMatomoEvent({
          category: 'Page',
          action: '货值管理-货值审批',
          name: '货值管理-货值审批',
        });
        if (data && data.result) {
          window.open(
            `${window.location.origin}/#/common/approve?action=modify&projectId=${match.params.project}`,
          );
        }
      },
    });
  };
  // End---跳转发起审批

  // 根据高级筛选按钮显示隐藏判断表格的高度
  subtractHeight = expandForm => {
    this.setState({
      subtractHeight: expandForm ? '274px' : '210px',
    });
  };

  /**
   * @Descripttion: 打印考核版标签
   * @param {*} params
   * @return {*}
   */
  clicksetVersionAssessment = params => {
    const { loading } = this.state;
    showConfirm(
      () => {
        this.setState({
          loading: {
            ...loading,
            assessment: true,
          },
        });
        apis
          .priceVersionAssessmentLableUsingPUT({ params: { versionId: params.version } })
          .then(result => {
            if (result && result.code * 1 && result.data === 'ok') {
              message.success(result.message);
              this.getVersions(this.props);
              this.getItems(this.props);
              this.setState({
                loading: {
                  ...loading,
                  assessment: false,
                },
              });
            }
          });
      },
      '设置考核版',
      '确定将此版本设为考核版吗？',
    );
  };

  /**
   * @Descripttion: 创建版本
   * @param {*}
   */
  clickCreateVersion = () => {
    showConfirm(
      async () => {
        const { level1, level2, project, stage, category } = this.props.match.params;

        const params = {
          projectFid: stage,
          versionType: category,
        };

        const response = await apis.createPriceVersionUsingPOST({ params });

        if (response.code === 1) {
          message.success(
            response.message,
            1,
            this.getVersions(this.props, versions => {
              let url = null;
              if (_.isEmpty(versions)) {
                url = `/ValueManage/PriceManage/${level1}/${level2}/${project}/${stage}/${category}`;
                this.setState({ emptyMsg: '版本不存在，请先创建新版本' });
              } else {
                url = `/ValueManage/PriceManage/${level1}/${level2}/${project}/${stage}/${category}/${versions[0].versionId}/edit`;
              }
              if (url) router.replace(url);
            }),
          );
        }
      },
      '创建货值填报版本',
      '点击确认后创建货值填报版本',
    );
  };

  /**
   * @Descripttion: 创建异常版本
   * @param {*}
   */
  clickCreateExceptionVersion = () => {
    showConfirm(
      async () => {
        const { level1, level2, project, stage, category } = this.props.match.params;

        const params = {
          projectFid: stage,
          versionType: category,
        };

        const response = await apis.exceptionPriceVersionUsingPOST({ params });

        if (response.code === 1) {
          message.success(
            response.message,
            1,
            this.getVersions(this.props, versions => {
              let url = null;
              if (_.isEmpty(versions)) {
                url = `/ValueManage/PriceManage/${level1}/${level2}/${project}/${stage}/${category}`;
                this.setState({ emptyMsg: '版本不存在，请先创建新版本' });
              } else {
                url = `/ValueManage/PriceManage/${level1}/${level2}/${project}/${stage}/${category}/${versions[0].versionId}/edit`;
              }
              if (url) router.replace(url);
            }),
          );
        }
      },
      '创建货值填报异常版本',
      '点击确认后创建货值填报异常版本',
    );
  };

  /**
   * @Descripttion: 创建普调版本
   * @param {*}
   * @return {*}
   */
  clickCreatePopularTuneVersion = () => {
    showConfirm(
      async () => {
        const { level1, level2, project, stage, category } = this.props.match.params;

        const params = {
          projectFid: stage,
          versionType: category,
        };

        const response = await apis.batchAdjustPriceVersionPOST({ params });

        if (response.code === 1) {
          message.success(
            response.message,
            1,
            this.getVersions(this.props, versions => {
              let url = null;
              if (_.isEmpty(versions)) {
                url = `/ValueManage/PriceManage/${level1}/${level2}/${project}/${stage}/${category}`;
                this.setState({ emptyMsg: '版本不存在，请先创建新版本' });
              } else {
                url = `/ValueManage/PriceManage/${level1}/${level2}/${project}/${stage}/${category}/${versions[0].versionId}/edit`;
              }
              if (url) router.replace(url);
            }),
          );
        }
      },
      '创建货值填报普调版本',
      '点击确认后创建货值填报普调版本',
    );
  };

  /**
   * @Descripttion: 删除版本
   * @param {*}
   * @return {*}
   */
  clickDeleteVersion = () => {
    showConfirm(
      async () => {
        const { level1, level2, project, stage, category, version } = this.props.match.params;
        const params = {
          versionId: version,
        };
        const response = await apis.deletePriceVersionUsingDELETE({ params });
        if (response.code === 1) {
          message.success(
            response.message,
            1,
            this.getVersions(this.props, versions => {
              let url = null;
              if (_.isEmpty(versions)) {
                url = `/ValueManage/PriceManage/${level1}/${level2}/${project}/${stage}/${category}`;
                this.setState({ emptyMsg: '版本不存在，请先创建新版本' });
              } else {
                url = `/ValueManage/PriceManage/${level1}/${level2}/${project}/${stage}/${category}/${versions[0].versionId}`;
              }
              if (url) router.replace(url);
            }),
          );
        }
      },
      '删除版本',
      '点击确认删除当前版本',
    );
  };

  /**
   * @Descripttion: 点击批量编辑普调均价
   * @param {*}
   * @return {*}
   */
  clickBatchOperation = () => {
    this.setState({
      showCopyComponent: true,
      // rowData,
    });
  };

  /**
   * @Descripttion: 保存
   * @param {*}
   * @return {*}
   */
  clickSave = () => {
    const { items, match } = this.props;
    // 是普调版本 如果存在上下限超过 正负20% 就不可以保存
    if (items.versionDetail?.batchAdjust && items.ptBatchData.length > 0) {
      const isAll = _.filter(items.initPtBatchData, x => Math.abs(x.range) > 20);
      if (isAll.length > 0) return message.warning('均价调整已超过正负 20%');
    }
    showConfirm(
      async () => {
        const params = treeUtils.getItemsForSave(_.cloneDeep(items.searched), items.all);
        params.versionId = match.params.version;
        params.versionType = match.params.category;
        const response = await apis.saveWarPlanPriceVersionUsingPUT({ data: params });
        if (response?.code === 1) {
          message.success(response.message, 1, () => {
            router.push(this.props.match.url.replace('/edit', ''));
          });
        }
      },
      '保存当前编辑',
      '点击确认后保存当前编辑数据',
    );
    return null;
  };

  handleCopyPriceClose() {
    this.setState({
      showCopyComponent: false,
      rowData: {},
    });
  }

  showCopyHouseComponent(rowData) {
    const { all } = this.props.items;
    const allData = _.cloneDeep(all);
    const { isMarketing } = this.state;
    // 楼栋下是否有面积段  过滤其它 e.areaPart !== '其它' 已删除的 e.isDeleted !== true
    // _.differenceWith([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }],_.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'))
    let areaParts = _.filter(
      allData,
      e => e.pid === rowData.id && e.areaPart !== '其它' && e.isDeleted !== true,
    );
    // 战规后操盘存在2个相同面积段情况（归集和拆分） 合并相同均价、货值、可售面积、套数信息
    if (_.differenceWith(areaParts, _.unionBy(areaParts, 'areaPart')).length) {
      _.forEach(areaParts, data => {
        // 套数
        data.num_house = this.renderSum(areaParts, 'num_house', data.areaPart);
        // 均价
        data.averagePrice_house = _.round(
          this.renderSum(areaParts, 'sum_house', data.areaPart) /
            this.renderSum(areaParts, 'saleArea', data.areaPart),
        );
        // 货值
        data.sum_house = _.round(this.renderSum(areaParts, 'sum_house', data.areaPart));
        // 可售面积
        data.saleArea = _.round(this.renderSum(areaParts, 'saleArea', data.areaPart), 2);
      });
      areaParts = _.unionBy(areaParts, 'areaPart');
      console.log(areaParts, 'areaParts');
    }
    // 战规后的货值版本中非车位产品构成下楼栋的面积段有均价未填写时，点击复制按钮，仍跳出复制面积段弹层（应提示面积段均价未全部填写）
    if (!rowData.averagePrice_house) {
      message.warning('请填写均价');
      return;
    }
    // if (_.filter(rowData.children, { averagePrice_house: 0 }).length > 0) {
    //   message.warning('面积段均价未全部填写');
    //   return;
    // }

    if (!areaParts.length && isMarketing) {
      message.warning('请新增面积段');
      return;
    }
    // 楼栋下面积段存在未选择面积段
    const hasareaPart = _.filter(
      rowData.children,
      e => e.areaPart === '请选择面积段' && e.isDeleted !== true,
    ).length;
    if (hasareaPart) {
      message.warning('该楼栋下有未选择的面积段');
      return;
    }
    this.setState({
      showCopyComponent: true,
      copyAreaParts: areaParts,
      rowData,
    });
  }

  renderSum(data, key, areaPart) {
    return this.sumBy(_.filter(data, { areaPart }), result => result[key]);
  }

  render() {
    const {
      fixedColumns,
      showCopyComponent,
      rowData,
      copyAreaParts,
      subtractHeight,
      titleTree,
    } = this.state;
    const treeData = this.props.items.searched;
    const isBatchAdjust = Boolean(this.props.items.versionDetail?.batchAdjust);
    const { edit, category, project } = this.props.match.params;
    const { expandedRowKeys, isMarketing } = this.props.items;
    const headerRenderer = utils.getHeaderRenderer(titleTree, 1);
    let drawerTitle = '';
    let drawerWidth = 0;
    // category === 'investment' || !isMarketing ? 670 : 600
    if (isBatchAdjust) {
      drawerTitle = '批量调整均价';
      drawerWidth = 830;
    } else if (category === 'investment' || (!isMarketing && category !== 'investment')) {
      drawerTitle = '复制价格';
      drawerWidth = 670;
    } else {
      drawerTitle = '复制面积段';
      drawerWidth = 600;
    }
    return (
      <PageHeaderWrapper
        className="page-header"
        breadcrumb={null}
        title={<ProjectsPath {...this.props} />}
        tags={!edit ? <CurrentStage {...this.props} /> : null}
        extra={
          !edit ? (
            <>
              <AuthorizedButton authority="HZTB_INITIATE_APPROVAL">
                <Button type="primary" onClick={() => this.handlerApprove('normal_approve')}>
                  发起审批
                </Button>
              </AuthorizedButton>
              {category === 'dynamic' && (
                <AuthorizedButton authority="HZTB_INITIATE_UNIVERSAL_APPROVAL">
                  <Button type="primary" onClick={() => this.handlerApprove('pt_approve')}>
                    发起普调审批
                  </Button>
                </AuthorizedButton>
              )}
              <AuthorizedButton authority="HZTB_APPROVAL_RECORD">
                <Button
                  onClick={() => {
                    router.push(`/ValueManage/PriceManage/ProjectValue/${project}`);
                  }}
                >
                  审批记录
                </Button>
              </AuthorizedButton>
            </>
          ) : (
            <>
              <Button type="primary" disabled={!this.props.items.canSave} onClick={this.clickSave}>
                保存
              </Button>
              <Button
                onClick={() => {
                  showConfirm(
                    () => router.push(this.props.match.url.replace('/edit', '')),
                    '确定要取消编辑?',
                    '取消后本次编辑内容将不保存。',
                  );
                }}
              >
                取消
              </Button>
            </>
          )
        }
      >
        <Card className="page-header-card">
          <Drawer
            width={drawerWidth}
            onClose={() => this.handleCopyPriceClose()}
            visible={showCopyComponent}
            title={drawerTitle}
          >
            {isBatchAdjust ? (
              <BatchEditComponent
                width={drawerWidth}
                onClose={e => this.handleCopyPriceClose(e)}
                {...this.props}
                showCopyComponent
              />
            ) : (
              <>
                {category === 'investment' ? (
                  <CopyPriceComponent
                    onclick={e => this.handleCopyClick(e)}
                    onClose={e => this.handleCopyPriceClose(e)}
                    rowData={rowData}
                    width={drawerWidth}
                    copyAreaParts={copyAreaParts}
                    {...this.props}
                  />
                ) : (
                  <>
                    {!isMarketing && category !== 'investment' ? (
                      <CopyHousePriceComponent
                        onclick={e => this.handleCopyClick(e)}
                        onClose={e => this.handleCopyPriceClose(e)}
                        rowData={rowData}
                        width={drawerWidth}
                        isMarketing={isMarketing}
                        copyAreaParts={copyAreaParts}
                        {...this.props}
                      />
                    ) : (
                      <CopyHouseComponent
                        onclick={e => this.handleCopyClick(e)}
                        onClose={e => this.handleCopyPriceClose(e)}
                        rowData={rowData}
                        width={drawerWidth}
                        isMarketing={isMarketing}
                        copyAreaParts={copyAreaParts}
                        {...this.props}
                      />
                    )}
                  </>
                )}
              </>
            )}
          </Drawer>
          <PageTop
            clickCreateVersion={this.clickCreateVersion} // 创建版本
            clickCreateExceptionVersion={this.clickCreateExceptionVersion} // 创建异常版本
            clickCreatePopularTuneVersion={this.clickCreatePopularTuneVersion} // 创建普调版本
            clickDeleteVersion={this.clickDeleteVersion} // 删除版本
            clicksetVersionAssessment={this.clicksetVersionAssessment} // 打印考核版标签
            clickBatchOperation={this?.clickBatchOperation} // 点击批量编辑普调
            expandForm={this.subtractHeight}
            {...this.props}
            upData={() => {
              this.getVersions(this.props);
              this.getItems(this.props);
            }}
          />
          {this.props.match.params.version && fixedColumns.length > 0 && treeData.length > 0 ? (
            <BaseTable
              headerHeight={[30, 60]}
              headerRenderer={headerRenderer}
              subtractHeight={subtractHeight}
              defaultExpandedRowKeys={expandedRowKeys}
              expandColumnKey="name"
              fixedColumns={fixedColumns}
              treeData={treeData}
            />
          ) : (
            <PageEmpty emptyTitle={this.state.emptyMsg} />
          )}
        </Card>
      </PageHeaderWrapper>
    );
  }
}
